#include "etcder.hpp"
#include "channel.hpp"
#include "aip-cpp-sdk/speech.h"
#include "speech.pb.h"
#include <gflags/gflags.h>
#include <thread>
#include <iostream>
#include <string>

DEFINE_bool(log_mode, false, "程序的运行模式: true-发布模式 false-调试模式");
DEFINE_string(log_file, "", "发布模式下，制定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下，制定日志的输出等级");

DEFINE_string(etcd_host, "127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监测根目录");

DEFINE_string(service, "/service/speech_service", "服务名称");

void online(const std::string &service_name, const std::string &service_host)
{
    LOG_INFO("服务[{}]-[{}]上线", service_name, service_host);
}
void offline(const std::string &service_name, const std::string &service_host)
{
    LOG_INFO("服务[{}]-[{}]下线", service_name, service_host);
}
int main(int argc, char *argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    bite_im::initLogger(FLAGS_log_mode, FLAGS_log_file, FLAGS_log_level);

    // 构造Rpc服务管理对象
    auto manager = std::make_shared<bite_im::ServiceManager>();
    manager->declareService(FLAGS_service);
    // 构造服务发现对象
    auto put_cb = std::bind(&bite_im::ServiceManager::onServiceOnline, manager.get(),
                            std::placeholders::_1, std::placeholders::_2);
    auto del_cb = std::bind(&bite_im::ServiceManager::onServiceOffLine, manager.get(),
                            std::placeholders::_1, std::placeholders::_2);
    auto discoverer = std::make_shared<bite_im::Discovery>(FLAGS_base_service, FLAGS_etcd_host, put_cb, del_cb);

    // 获取服务信道
    auto channel = manager->choose(FLAGS_service);
    if (channel.get() == nullptr)
    {
        return -1;
    }
    // 进行Rpc调用
    // EchoService服务存根
    auto stub = std::make_shared<bite_im::SpeechService_Stub>(channel.get());
    // 进行rpc调用
    auto req = std::make_shared<bite_im::SpeechRecognitionReq>();
    // 获取语音文件数据
    std::string file_name = "test.pcm";
    std::string file_content;
    // aip::get_file_content("listen.pcm", &file_content);  // 也是报错
    aip::get_file_content(file_name.c_str(), &file_content);

    req->set_speech_content(file_content);
    req->set_request_id("432248");
    auto resp = std::make_shared<bite_im::SpeechRecognitionRsp>();
    // 获取一个rpc操作对象
    auto cntl = std::make_shared<brpc::Controller>(); // ??
    // stub调用我们实现的服务类ipml的接口
    stub->SpeechRecognition(cntl.get(), req.get(), resp.get(), nullptr);
    if (cntl->Failed() == true)
    {
        std::cout << "Rpc调用失败：" << cntl->ErrorText() << std::endl;
    }
    if (resp->success() == false)
    {
        // 语音转文字失败, 原因[语音识别失败，原因[invalid audio length]]
        // 解决这个错误我们把这个test.pcm放进build中
        std::cout << "语音转文字失败, 原因[" << resp->errmsg() << "]" << std::endl;
        return -1;
    }
    std::cout << "响应id为: " << resp->request_id() << ", 语音转文字结果为[" << resp->recognition_result() << "]" << std::endl;

    std::this_thread::sleep_for(std::chrono::seconds(10));
}
